import datetime
import json
from apps.pay.order.dao import OrderDao
from apps.pay.recordIncomesLocked.dao import RecordIncomesLockedDao
from apps.merchant.sku.dao import SkuDao



def checkOrders():
    # 取消10分钟之前待支付订单
    _orders = OrderDao().findAll().filter(orderStatus='WAIT_PAY', createTime__lt=datetime.datetime.now()-datetime.timedelta(minutes=10))
    if _orders.exists():
        # 取消之后，释放库存
        for order in _orders:
            if order.content:
                content = json.loads(order.content)
                for item in content:
                    if item.get('sku'):
                        SkuDao().addStock(item.get('sku'), item.get('payCount'))
    
        _orders.update(orderStatus='CANCEL')

# 每分钟解锁到期资产
def unlockedProperay():
    _properays = RecordIncomesLockedDao().findAll().filter(orderStatus='LOCKED', unlockedTime__lt=datetime.datetime.now())
    if _properays.exists():
        _properays.update(orderStatus='UNLOCKED')